package com.toutoushidao.ssm.exception;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.toutoushidao.ssm.dto.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 错误信息统一处理
 * 对未处理的错误信息做一个统一处理
 * @author laodun
 *
 */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {

	private final Logger LOG = LoggerFactory.getLogger(this.getClass());

	@Override
	@ResponseBody
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		LOG.error("访问" + request.getRequestURI() + " 发生错误, 错误信息:" + ex.getMessage());

		ex.printStackTrace();

        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<String, Object>();

        if (ex instanceof BizException) {
            //如果是BizException取出Code和message分别处理
            BizException bizException = (BizException) ex;
            attributes.put("code", bizException.getResult().getCode());
            attributes.put("message", bizException.getResult().getMsg());
        } else {
            attributes.put("code", String.valueOf(ResultEnum.EXCEPTION_SYSTEM.getCode()));
            attributes.put("message", String.valueOf(ResultEnum.EXCEPTION_SYSTEM.getMsg()));
        }

        view.setAttributesMap(attributes);
        mv.setView(view);

        return mv;
	}
}
